const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');
const User = require('./User');
const Note = require('./Note');
const Video = require('./Video');

const Comment = sequelize.define('Comment', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  content: {
    type: DataTypes.TEXT,
    allowNull: false
  },
  user_id: {
    type: DataTypes.STRING(255),
    allowNull: false,
    references: {
      model: User,
      key: 'id'
    }
  },
  note_id: {
    type: DataTypes.STRING(255),
    references: {
      model: Note,
      key: 'id'
    }
  },
  video_id: {
    type: DataTypes.STRING(255),
    references: {
      model: Video,
      key: 'id'
    }
  },
  created_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updated_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    onUpdate: DataTypes.NOW
  }
}, {
  tableName: 'comments',
  timestamps: false,
  validate: {
    atLeastOneNotNull() {
      if (!this.note_id && !this.video_id) {
        throw new Error('note_id 或 video_id 必须有一个不为空');
      }
    }
  }
});

// 关联
Comment.belongsTo(User, { foreignKey: 'user_id', onDelete: 'CASCADE' });
Comment.belongsTo(Note, { foreignKey: 'note_id', onDelete: 'CASCADE' });
Comment.belongsTo(Video, { foreignKey: 'video_id', onDelete: 'CASCADE' });

module.exports = Comment;